package de.fsujena.chat_pi.server.userInterface.GUI;

import de.fsujena.chat_pi.ressources.Room;
import de.fsujena.chat_pi.ressources.User;
import de.fsujena.chat_pi.ressources.User.ROLE;
import de.fsujena.chat_pi.server.Server;

import javax.swing.DefaultListModel;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.GroupLayout;
import javax.swing.ListModel;
import javax.swing.SwingUtilities;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JOptionPane;
import javax.swing.JSplitPane;
import javax.swing.JPanel;
import javax.swing.JTextPane;
import javax.swing.JTree;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.event.ListDataEvent;
import javax.swing.event.ListDataListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.StyledDocument;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeNode;

import java.awt.CardLayout;
import java.awt.List;

import javax.swing.JTabbedPane;
import javax.swing.JButton;
import javax.swing.JTextField;
import javax.swing.JScrollPane;
import javax.swing.ScrollPaneConstants;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Observable;
import java.util.Observer;

import javax.swing.ImageIcon;
import java.awt.Toolkit;
import javax.swing.JPopupMenu;
import java.awt.Component;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JList;
import javax.swing.ListSelectionModel;


public class MainWindow {

	private JFrame frmServer;
	private JTextField messageTextField;
	private Server serverObject;
	private StyledDocument doc;
	public JTree userRoomTree ;
	public JTree roomTree;
	JList userList;
	JMenu mnServer;

//	/**
//	 * Launch the application.
//	 */
//	public static void main(String[] args) {
//		EventQueue.invokeLater(new Runnable() {
//			public void run() {
//				
//			}
//		});
//	}
	
	public MainWindow(Server serverObject) {
		this.serverObject = serverObject;

		initialize();

		frmServer.setVisible(true);
		
	}

	/**
	 * @wbp.parser.entryPoint
	 *
	 * Create the application.
	 */
	public MainWindow() {
		try {
			MainWindow window = new MainWindow(serverObject);
			window.frmServer.setVisible(true);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Initialize the contents of the frame.
	 */
	private void initialize() {
		// Main Frame
		frmServer = new JFrame();
		//frmServer.setIconImage(Toolkit.getDefaultToolkit().getImage(MainWindow.class.getResource("/res/red_circle.png")));
		frmServer.setTitle("Server");
		frmServer.setBounds(100, 100, 800, 600);
		frmServer.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		//ServerStateObserver stateObserver = new ServerStateObserver();
		//serverObject.addObserver(stateObserver);
		
		// Menu
		JMenuBar menuBar = new JMenuBar();
		frmServer.setJMenuBar(menuBar);
		
		mnServer = new JMenu("Server");
		//mnServer.setIcon(new ImageIcon(MainWindow.class.getResource("/res/red_circle_small.png")));
		//mnServer.setIcon(new ImageIcon(MainWindow.class.getResource("/com/sun/java/swing/plaf/gtk/resources/gtk-no-4.png")));
		menuBar.add(mnServer);
		
		JMenuItem mntmStart = new JMenuItem("Start");
		mntmStart.addActionListener(new ServerStartListener());
		mnServer.add(mntmStart);
		
		JMenuItem mntmStop = new JMenuItem("Stop");
		mntmStop.addActionListener(new ServerStopListener());
		mnServer.add(mntmStop);
		
		JMenuItem mntmSettings = new JMenuItem("Settings");
		mntmSettings.addActionListener(new OpenSettingsListener());
		mnServer.add(mntmSettings);
		
		JMenuItem mntmExit = new JMenuItem("Exit");
		mntmExit.addActionListener(new ServerExitListener());
		
		JMenuItem mntmDeleteHistory = new JMenuItem("Delete History");
		mntmDeleteHistory.addActionListener(new DeleteHistory());
		mnServer.add(mntmDeleteHistory);
		mnServer.add(mntmExit);
		
		frmServer.getContentPane().setLayout(new CardLayout(0, 0));
		
		JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
		frmServer.getContentPane().add(tabbedPane, "name_595804579167680");
		
		JSplitPane chatMain = new JSplitPane();
		tabbedPane.addTab("Chat", null, chatMain, null);
		tabbedPane.setEnabledAt(0, true);
		chatMain.setResizeWeight(0.8);
		
		JPanel messageBox = new JPanel();
		chatMain.setLeftComponent(messageBox);
		
		JPanel messageSendPanel = new JPanel();
		
		JScrollPane messageViewPanel = new JScrollPane();
		messageViewPanel.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
		GroupLayout gl_messageBox = new GroupLayout(messageBox);
		gl_messageBox.setHorizontalGroup(
			gl_messageBox.createParallelGroup(Alignment.LEADING)
				.addGroup(Alignment.TRAILING, gl_messageBox.createSequentialGroup()
					.addContainerGap()
					.addGroup(gl_messageBox.createParallelGroup(Alignment.TRAILING)
						.addComponent(messageViewPanel, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 565, Short.MAX_VALUE)
						.addComponent(messageSendPanel, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 468, Short.MAX_VALUE))
					.addContainerGap())
		);
		gl_messageBox.setVerticalGroup(
			gl_messageBox.createParallelGroup(Alignment.LEADING)
				.addGroup(Alignment.TRAILING, gl_messageBox.createSequentialGroup()
					.addContainerGap()
					.addComponent(messageViewPanel, GroupLayout.DEFAULT_SIZE, 363, Short.MAX_VALUE)
					.addPreferredGap(ComponentPlacement.RELATED)
					.addComponent(messageSendPanel, GroupLayout.PREFERRED_SIZE, 26, GroupLayout.PREFERRED_SIZE)
					.addContainerGap())
		);
		
		JTextPane messageViewTextPanel = new JTextPane();
		messageViewTextPanel.setEditable(false);
		messageViewPanel.setViewportView(messageViewTextPanel);
		
		// Define document
		doc = messageViewTextPanel.getStyledDocument();
		
		messageTextField = new JTextField();
		messageTextField.addActionListener(new SendMsgListener());
		//messageTextField.setColumns(10);
		
		JButton messageSendButton = new JButton("Send");
		messageSendButton.addActionListener(new SendMsgListener());
		
		GroupLayout gl_messageSendPanel = new GroupLayout(messageSendPanel);
		gl_messageSendPanel.setHorizontalGroup(
			gl_messageSendPanel.createParallelGroup(Alignment.LEADING)
				.addGroup(Alignment.TRAILING, gl_messageSendPanel.createSequentialGroup()
					.addComponent(messageTextField, GroupLayout.DEFAULT_SIZE, 398, Short.MAX_VALUE)
					.addPreferredGap(ComponentPlacement.RELATED)
					.addComponent(messageSendButton))
		);
		gl_messageSendPanel.setVerticalGroup(
			gl_messageSendPanel.createParallelGroup(Alignment.LEADING)
				.addComponent(messageTextField, GroupLayout.DEFAULT_SIZE, 50, Short.MAX_VALUE)
				.addComponent(messageSendButton, GroupLayout.DEFAULT_SIZE, 50, Short.MAX_VALUE)
		);
		messageSendPanel.setLayout(gl_messageSendPanel);
		messageBox.setLayout(gl_messageBox);
		
		JSplitPane userRoomPanel = new JSplitPane();
		userRoomPanel.setResizeWeight(0.5);
		userRoomPanel.setOrientation(JSplitPane.VERTICAL_SPLIT);
		chatMain.setRightComponent(userRoomPanel);
		
		JScrollPane userRoomInfoPanel = new JScrollPane();
		userRoomPanel.setRightComponent(userRoomInfoPanel);
		
		JTextPane userRoomInfo = new JTextPane();
		userRoomInfo.setEditable(false);
		userRoomInfoPanel.setViewportView(userRoomInfo);
		
		JScrollPane userRoomTreePanel = new JScrollPane();
		userRoomPanel.setLeftComponent(userRoomTreePanel);
		
		//JTree userRoomTree = new JTree(serverObject.roomManager.foyer);
		userRoomTree = new JTree(serverObject.roomManager.foyer);
		userRoomTree.setAutoscrolls(true);
		userRoomTree.setDragEnabled(true);
		userRoomTree.setEditable(true);
		userRoomTreePanel.setViewportView(userRoomTree);
		
		JSplitPane userMain = new JSplitPane();
		userMain.setResizeWeight(0.8);
		tabbedPane.addTab("User Management", null, userMain, null);
		
		JScrollPane userListPanel = new JScrollPane();
		userMain.setLeftComponent(userListPanel);
				
		userList = new JList(serverObject.userManager.userListModel);
		userList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		userListPanel.setViewportView(userList);
		
		JScrollPane userMngPanel = new JScrollPane();
		userMain.setRightComponent(userMngPanel);
		
		JSplitPane roomMain = new JSplitPane();
		roomMain.setResizeWeight(0.8);
		tabbedPane.addTab("Room Management", null, roomMain, null);
		
		JScrollPane roomTreePanel = new JScrollPane();
		roomMain.setLeftComponent(roomTreePanel);
		
		roomTree = new JTree(serverObject.roomManager.foyer);
		roomTreePanel.setViewportView(roomTree);
		
		JPopupMenu popupRoomTreeMenu = new JPopupMenu();
		addRoomTreePopup(roomTree, popupRoomTreeMenu);
		
		addRoomTreePopup(userRoomTree, popupRoomTreeMenu);
		
		JPopupMenu popupUserMenu = new JPopupMenu();
		addUserPopup(userList, popupUserMenu);		
		
		JScrollPane roomMngPanel = new JScrollPane();
		roomMain.setRightComponent(roomMngPanel);
	}
	
	class ServerStateObserver implements Observer {
		public void update(Observable observed, Object state) {
			System.out.println("observed");
			if ((observed instanceof Server) && (state instanceof Boolean)) {
				if ((Boolean)state) {
					frmServer.setIconImage(Toolkit.getDefaultToolkit().getImage(MainWindow.class.getResource("/res/green_circle.png")));
					mnServer.setIcon(new ImageIcon(MainWindow.class.getResource("/res/green_circle_small.png")));
				} else {
					frmServer.setIconImage(Toolkit.getDefaultToolkit().getImage(MainWindow.class.getResource("/res/red_circle.png")));
					mnServer.setIcon(new ImageIcon(MainWindow.class.getResource("/res/red_circle_small.png")));
				}
			}
		}
	}
	
	class ServerStartListener implements ActionListener {
		@Override
		public void actionPerformed(ActionEvent e) {
			if(!serverObject.isStarted)
				serverObject.startServer();
		}
	}
	class DeleteHistory implements ActionListener {
		@Override
		public void actionPerformed(ActionEvent e) {
			serverObject.msgArray.clear();
			serverObject.saveHistory();
			try {
				doc.remove(0, doc.getLength());
			} catch (BadLocationException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}
	}
	
	class ServerStopListener implements ActionListener {
		@Override
		public void actionPerformed(ActionEvent e) {
			if(serverObject.isStarted)
				serverObject.stopServer();
		}
	}
	
	class ServerExitListener implements ActionListener {
		@Override
		public void actionPerformed(ActionEvent arg0) {
			if(serverObject.isStarted)
				serverObject.stopServer();
			
			frmServer.dispose();
			
			serverObject.exit();
		}
	}
	
	class SendMsgListener implements ActionListener {
		@Override
		public void actionPerformed(ActionEvent arg0) {
			if(serverObject.isStarted) {
				String msgString = messageTextField.getText();
				
				if (!msgString.equals("")) {
					if(msgString.startsWith("$")){
					serverObject.commander(msgString);	
					}else{
					serverObject.networkListener.sendServerTextMessage(msgString);
					serverObject.ui.postOwnTextMessage(msgString);
					}
					messageTextField.setText("");
				}
			}
		}
	}
	
	class OpenSettingsListener implements ActionListener {
		@Override
		public void actionPerformed(ActionEvent arg0) {
			try {
				SettingsWindow dialog = new SettingsWindow(serverObject);
				dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
				dialog.setVisible(true);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	class CreateRoom implements ActionListener {
		@Override
		public void actionPerformed(ActionEvent arg0) {
			Room node = (Room)  roomTree.getLastSelectedPathComponent();
			java.util.List<String> path = new ArrayList<String>();
			path.clear();
			for(int i=0;i<node.getDir().size();i++){
			path.add(node.getDir().get(i));
			}
			String newRoom = (String) JOptionPane.showInputDialog(frmServer, "Type a name for the new room.", "Create New Room", JOptionPane.QUESTION_MESSAGE);
			if (newRoom!=null && !newRoom.isEmpty()) {
				path.add(newRoom);
				serverObject.roomManager.createRoom(path,null);
			}
		}
	}
	
	class RenameRoom implements ActionListener {
		@Override
		public void actionPerformed(ActionEvent arg0) {
			Room node = (Room)  roomTree.getLastSelectedPathComponent();
			java.util.List<String> path = new ArrayList<String>();
			path.clear();
			for(int i=0;i<node.getDir().size();i++){
			path.add(node.getDir().get(i));
			}
			String newName = (String) JOptionPane.showInputDialog(frmServer, "Type the new name for the room \"" + path.get(path.size()-1) + "\".", "Create New Room", JOptionPane.QUESTION_MESSAGE);
			if (newName!=null && !newName.isEmpty()) {
				path.add(newName);
				serverObject.roomManager.changeRoomName(path);
			}
		}
	}
	
	class DeleteRoom implements ActionListener {
		@Override
		public void actionPerformed(ActionEvent arg0) {
			Room node = (Room) roomTree.getLastSelectedPathComponent();
			java.util.List<String> path = node.getDir();
			
			if (JOptionPane.showConfirmDialog(frmServer, "Do you really want to remove the room?", "Remove Room", JOptionPane.YES_NO_OPTION) == 0) {			
				try {
					serverObject.roomManager.removeRoom(path);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	class WarnUser implements ActionListener {
		User user;
		public WarnUser(User user) {
			this.user = user;
		}
		
		@Override
		public void actionPerformed(ActionEvent arg0) {
			if (user == null) {
				user = (User) roomTree.getLastSelectedPathComponent();
			}
			
			String username = user.name;
			
			String reason = (String) JOptionPane.showInputDialog(frmServer, "Type the for the warning:", "Warn User", JOptionPane.QUESTION_MESSAGE);
			
			if (!reason.isEmpty()) {			
				try {
					serverObject.userManager.warnUser(username,reason);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	class KickUser implements ActionListener {
		User user;
		public KickUser(User user) {
			this.user = user;
		}

		@Override
		public void actionPerformed(ActionEvent arg0) {
			if (user == null) {
				user = (User) roomTree.getLastSelectedPathComponent();
			}
			
			String username = user.name;
			
			if (JOptionPane.showConfirmDialog(frmServer, "Do you really want to kick the user?", "Kick User", JOptionPane.YES_NO_OPTION) == 0) {			
				try {
					serverObject.userManager.kickUser(username);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	class BannUser implements ActionListener {
		User user;
		public BannUser(User user) {
			this.user = user;
		}
		
		@Override
		public void actionPerformed(ActionEvent arg0) {
			if (user == null) {
				user = (User) roomTree.getLastSelectedPathComponent();
			}
			
			String username = user.name;
			
			if (JOptionPane.showConfirmDialog(frmServer, "Do you really want to bann the user?", "Bann User", JOptionPane.YES_NO_OPTION) == 0) {			
				try {
					serverObject.userManager.bannUser(username);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	class UnbannUser implements ActionListener {
		User user;
		public UnbannUser(User user) {
			this.user = user;
		}
		
		@Override
		public void actionPerformed(ActionEvent arg0) {
			if (user == null) {
				user = (User) roomTree.getLastSelectedPathComponent();
			}
			
			String username = user.name;
			
			if (JOptionPane.showConfirmDialog(frmServer, "Do you really want to unbann the user?", "Unbann User", JOptionPane.YES_NO_OPTION) == 0) {			
				try {
					serverObject.userManager.unbannUser(username);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	class RemoveUser implements ActionListener {
		User user;
		public RemoveUser(User user) {
			this.user = user;
		}
		
		@Override
		public void actionPerformed(ActionEvent arg0) {
			if (user == null) {
				user = (User) roomTree.getLastSelectedPathComponent();
			}
			
			String username = user.name;
			
			if (JOptionPane.showConfirmDialog(frmServer, "Do you really want to remove the user?", "Remove User", JOptionPane.YES_NO_OPTION) == 0) {			
				try {
					serverObject.userManager.removeUser(username);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	class UserRole implements ActionListener {
		User user;
		ROLE role;
		
		public UserRole(User user,ROLE role) {
			this.user = user;
			this.role = role;
		}
		
		@Override
		public void actionPerformed(ActionEvent arg0) {
			if (user == null) {
				user = (User) roomTree.getLastSelectedPathComponent();
			}
			
			String username = user.name;
			
			if (JOptionPane.showConfirmDialog(frmServer, "Do you really want to change the user role?", "Change User Role", JOptionPane.YES_NO_OPTION) == 0) {			
				try {
					serverObject.userManager.setUserRole(username, role);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	public void postMessage(String msgReceived, String userName, String msgString) { 
		try {
			String temp="["+userName.toUpperCase()+" ("+msgReceived+")]"+">> "+msgString+"\n";
			doc.insertString(doc.getLength(), temp, null);
			serverObject.msgArray.add(temp);
			serverObject.saveHistory();
		} catch (BadLocationException e) {
			e.printStackTrace();
		}
	}
	
	public void postOwnMessage(String msgReceived, String userName, String msgString) {
		try {
			String temp="["+userName.toUpperCase()+" ("+msgReceived+")]"+">> "+msgString+"\n";
			doc.insertString(doc.getLength(), temp, null);
			serverObject.msgArray.add(temp);
			serverObject.saveHistory();
		} catch (BadLocationException e) {
			e.printStackTrace();
		}
	}
	
	public void postText(String str){
		try {
			doc.insertString(doc.getLength(), str, null);
		} catch (BadLocationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	private void addRoomTreePopup(Component component, final JPopupMenu popup) {
		final JTree tree = (JTree) component;
		
		component.addMouseListener(new MouseAdapter() {
			public void mousePressed(MouseEvent e) {
				popup.removeAll();
				
				if (SwingUtilities.isRightMouseButton(e))  
				{  
				   int row = tree.getClosestRowForLocation(e.getX(), e.getY());  
				   tree.setSelectionRow(row);
				}
				
				if (e.isPopupTrigger()) {
					if (tree.getLastSelectedPathComponent() instanceof Room) {
						JMenuItem mntmCreateRoomHere = new JMenuItem("create room here");
						mntmCreateRoomHere.addActionListener(new CreateRoom());
						popup.add(mntmCreateRoomHere);
						
						JMenuItem mntmRenameRoom = new JMenuItem("rename room");
						mntmRenameRoom.addActionListener(new RenameRoom());
						popup.add(mntmRenameRoom);
						
						JMenuItem mntmDeleteRoom = new JMenuItem("delete room");
						mntmDeleteRoom.addActionListener(new DeleteRoom());
						popup.add(mntmDeleteRoom);
						
						showMenu(e);
					}
					
					if (tree.getLastSelectedPathComponent() instanceof User) {
						
						User user = (User) tree.getLastSelectedPathComponent();
						
						JMenuItem mntmWarnUser = new JMenuItem("warn user");
						mntmWarnUser.addActionListener(new WarnUser(user));
						popup.add(mntmWarnUser);
						
						JMenuItem mntmKickUser = new JMenuItem("kick user");
						mntmKickUser.addActionListener(new KickUser(user));
						popup.add(mntmKickUser);
						
						if (user.status == User.STATUS.NORMAL) {
							JMenuItem mntmBannUser = new JMenuItem("bann user");
							mntmBannUser.addActionListener(new BannUser(user));
							popup.add(mntmBannUser);
						}
						
						if (user.status == User.STATUS.BANNED) {
							JMenuItem mntmUnbannUser = new JMenuItem("unbann user");
							mntmUnbannUser.addActionListener(new UnbannUser(user));
							popup.add(mntmUnbannUser);
						}
						
						if (user.role != User.ROLE.ADMIN) {
							JMenuItem mntmAdminUser = new JMenuItem("make user admin");
							mntmAdminUser.addActionListener(new UserRole(user,User.ROLE.ADMIN));
							popup.add(mntmAdminUser);
						}
						
						if (user.role != User.ROLE.MODERATOR) {
							JMenuItem mntmModeratorUser = new JMenuItem("make user moderator");
							mntmModeratorUser.addActionListener(new UserRole(user,User.ROLE.MODERATOR));
							popup.add(mntmModeratorUser);
						}
						
						if (user.role != User.ROLE.STANDARD) {
							JMenuItem mntmStandardUser = new JMenuItem("make user standard user");
							mntmStandardUser.addActionListener(new UserRole(user,User.ROLE.STANDARD));
							popup.add(mntmStandardUser);
						}
						
						JMenuItem mntmRemoveUser = new JMenuItem("remove user");
						mntmRemoveUser.addActionListener(new RemoveUser(user));
						popup.add(mntmRemoveUser);
						
						showMenu(e);
					}
				}
			}
			public void mouseReleased(MouseEvent e) {
				if (e.isPopupTrigger()) {
					if (tree.getLastSelectedPathComponent() instanceof Room) {
						JMenuItem mntmCreateRoomHere = new JMenuItem("create room here");
						mntmCreateRoomHere.addActionListener(new CreateRoom());
						popup.add(mntmCreateRoomHere);
						
						JMenuItem mntmRenameRoom = new JMenuItem("rename room");
						mntmRenameRoom.addActionListener(new RenameRoom());
						popup.add(mntmRenameRoom);
						
						JMenuItem mntmDeleteRoom = new JMenuItem("delete room");
						mntmDeleteRoom.addActionListener(new DeleteRoom());
						popup.add(mntmDeleteRoom);
						
						showMenu(e);
					}
					
					if (tree.getLastSelectedPathComponent() instanceof User) {
						
						User user = (User) tree.getLastSelectedPathComponent();
						
						JMenuItem mntmWarnUser = new JMenuItem("warn user");
						mntmWarnUser.addActionListener(new WarnUser(user));
						popup.add(mntmWarnUser);
						
						JMenuItem mntmKickUser = new JMenuItem("kick user");
						mntmKickUser.addActionListener(new KickUser(user));
						popup.add(mntmKickUser);
						
						if (user.status == User.STATUS.NORMAL) {
							JMenuItem mntmBannUser = new JMenuItem("bann user");
							mntmBannUser.addActionListener(new BannUser(user));
							popup.add(mntmBannUser);
						}
						
						if (user.status == User.STATUS.BANNED) {
							JMenuItem mntmUnbannUser = new JMenuItem("unbann user");
							mntmUnbannUser.addActionListener(new UnbannUser(user));
							popup.add(mntmUnbannUser);
						}
						
						if (user.role != User.ROLE.ADMIN) {
							JMenuItem mntmAdminUser = new JMenuItem("make user admin");
							mntmAdminUser.addActionListener(new UserRole(user,User.ROLE.ADMIN));
							popup.add(mntmAdminUser);
						}
						
						if (user.role != User.ROLE.MODERATOR) {
							JMenuItem mntmModeratorUser = new JMenuItem("make user moderator");
							mntmModeratorUser.addActionListener(new UserRole(user,User.ROLE.MODERATOR));
							popup.add(mntmModeratorUser);
						}
						
						if (user.role != User.ROLE.STANDARD) {
							JMenuItem mntmStandardUser = new JMenuItem("make user standard user");
							mntmStandardUser.addActionListener(new UserRole(user,User.ROLE.STANDARD));
							popup.add(mntmStandardUser);
						}
						
						JMenuItem mntmRemoveUser = new JMenuItem("remove user");
						mntmRemoveUser.addActionListener(new RemoveUser(user));
						popup.add(mntmRemoveUser);
						
						showMenu(e);
					}
				
				}
			}
			private void showMenu(MouseEvent e) {
				popup.show(e.getComponent(), e.getX(), e.getY());
			}
		});
	}
	
	private void addUserPopup(Component component, final JPopupMenu popup) {
		final JList list = (JList) component;
		
		component.addMouseListener(new MouseAdapter() {
			public void mousePressed(MouseEvent e) {
				popup.removeAll();
				
				if (SwingUtilities.isRightMouseButton(e))  
				{  
					list.setSelectedIndex(list.locationToIndex(e.getPoint()));
				}
				
				if (e.isPopupTrigger()) {
					String itemName = (String) list.getSelectedValue();
					
					if (serverObject.userManager.checkUserExists(itemName)) {
						
						User user = serverObject.userManager.getUser(itemName);
						
						JMenuItem mntmWarnUser = new JMenuItem("warn user");
						mntmWarnUser.addActionListener(new WarnUser(user));
						popup.add(mntmWarnUser);
						
						JMenuItem mntmKickUser = new JMenuItem("kick user");
						mntmKickUser.addActionListener(new KickUser(user));
						popup.add(mntmKickUser);
						
						if (user.status == User.STATUS.NORMAL) {
							JMenuItem mntmBannUser = new JMenuItem("bann user");
							mntmBannUser.addActionListener(new BannUser(user));
							popup.add(mntmBannUser);
						}
						
						if (user.status == User.STATUS.BANNED) {
							JMenuItem mntmUnbannUser = new JMenuItem("unbann user");
							mntmUnbannUser.addActionListener(new UnbannUser(user));
							popup.add(mntmUnbannUser);
						}
						
						if (user.role != User.ROLE.ADMIN) {
							JMenuItem mntmAdminUser = new JMenuItem("make user admin");
							mntmAdminUser.addActionListener(new UserRole(user,User.ROLE.ADMIN));
							popup.add(mntmAdminUser);
						}
						
						if (user.role != User.ROLE.MODERATOR) {
							JMenuItem mntmModeratorUser = new JMenuItem("make user moderator");
							mntmModeratorUser.addActionListener(new UserRole(user,User.ROLE.MODERATOR));
							popup.add(mntmModeratorUser);
						}
						
						if (user.role != User.ROLE.STANDARD) {
							JMenuItem mntmStandardUser = new JMenuItem("make user standard user");
							mntmStandardUser.addActionListener(new UserRole(user,User.ROLE.STANDARD));
							popup.add(mntmStandardUser);
						}
						
						JMenuItem mntmRemoveUser = new JMenuItem("remove user");
						mntmRemoveUser.addActionListener(new RemoveUser(user));
						popup.add(mntmRemoveUser);
						
						showMenu(e);
					}
				}
			}
			public void mouseReleased(MouseEvent e) {
				if (e.isPopupTrigger()) {
					if (SwingUtilities.isRightMouseButton(e))  
					{  
						list.setSelectedIndex(list.locationToIndex(e.getPoint()));
					}
					
					if (e.isPopupTrigger()) {
						String itemName = (String) list.getSelectedValue();
						
						if (serverObject.userManager.checkUserExists(itemName)) {
							
							User user = serverObject.userManager.getUser(itemName);
							
							JMenuItem mntmWarnUser = new JMenuItem("warn user");
							mntmWarnUser.addActionListener(new WarnUser(user));
							popup.add(mntmWarnUser);
							
							JMenuItem mntmKickUser = new JMenuItem("kick user");
							mntmKickUser.addActionListener(new KickUser(user));
							popup.add(mntmKickUser);
							
							if (user.status == User.STATUS.NORMAL) {
								JMenuItem mntmBannUser = new JMenuItem("bann user");
								mntmBannUser.addActionListener(new BannUser(user));
								popup.add(mntmBannUser);
							}
							
							if (user.status == User.STATUS.BANNED) {
								JMenuItem mntmUnbannUser = new JMenuItem("unbann user");
								mntmUnbannUser.addActionListener(new UnbannUser(user));
								popup.add(mntmUnbannUser);
							}
							
							if (user.role != User.ROLE.ADMIN) {
								JMenuItem mntmAdminUser = new JMenuItem("make user admin");
								mntmAdminUser.addActionListener(new UserRole(user,User.ROLE.ADMIN));
								popup.add(mntmAdminUser);
							}
							
							if (user.role != User.ROLE.MODERATOR) {
								JMenuItem mntmModeratorUser = new JMenuItem("make user moderator");
								mntmModeratorUser.addActionListener(new UserRole(user,User.ROLE.MODERATOR));
								popup.add(mntmModeratorUser);
							}
							
							if (user.role != User.ROLE.STANDARD) {
								JMenuItem mntmStandardUser = new JMenuItem("make user standard user");
								mntmStandardUser.addActionListener(new UserRole(user,User.ROLE.STANDARD));
								popup.add(mntmStandardUser);
							}
							
							JMenuItem mntmRemoveUser = new JMenuItem("remove user");
							mntmRemoveUser.addActionListener(new RemoveUser(user));
							popup.add(mntmRemoveUser);
							
							showMenu(e);
						}
					}
				}
			}
			private void showMenu(MouseEvent e) {
				popup.show(e.getComponent(), e.getX(), e.getY());
			}
		});
	}
}
